package server

import (
	"context"
	"enjoy-joy/common/models/mysql"
	"enjoy-joy/common/models/redis"
	user "enjoy-joy/common/proto"
	"errors"
	"fmt"
	"math/rand"
	"time"
)

func SendSms(in *user.SendSmsReq) (*user.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	/*sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, errors.New(*sms.Body.Message)
	}*/
	redis.SendSmsSet("SendSms"+in.Source+in.Mobile, code)
	return &user.SendSmsResp{Greet: "发送成功"}, nil
}

func UserLoginOrRegister(in *user.UserLoginOrRegisterReq) (*user.UserLoginOrRegisterResp, error) {
	u := &mysql.User{}
	mobile, err := u.FindUserByMobile(in.Mobile)
	if err != nil {
		return nil, errors.New("手机号查询错误")
	}
	get := redis.SendSmsGet("SendSmsLogin" + in.Mobile)
	if get != int(in.Code) {
		return nil, errors.New("验证码错误")
	}
	if mobile.ID == 0 {
		fmt.Println("手机号未注册")
		err = u.CreateUser(in.Mobile)
		if err != nil {
			return nil, errors.New("注册失败")
		}
	}
	return &user.UserLoginOrRegisterResp{Greet: int64(mobile.ID)}, nil
}
func ClassList(in *user.ClassListReq) (*user.ClassListResp, error) {

	redis.Rdb.SetNX(context.Background(), "classnx", "1", time.Hour*24)
	c := &mysql.Class{}
	classes, err := c.FindClasses(int(in.Page), int(in.Pagesize))
	if err != nil {
		return nil, err
	}
	if classes == nil {
		return nil, err
	}
	fmt.Println(classes)
	var item []*user.ClassList
	for _, class := range classes {
		item = append(item, &user.ClassList{
			ClassName: class.ClassName,
			ClassNum:  class.ClassNum,
			ClassTime: class.ClassTime,
		})
	}
	redis.ClassL("classList", item)
	return &user.ClassListResp{List: item}, nil
}
